package com.wxy.controller;

import com.wxy.domain.MyException;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.javassist.ClassPath;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
@RequestMapping("img")
public class ImgController {
    @GetMapping("/imghtml")
    public String imghtml() {
        return "img";
    }

    @GetMapping("/image")
    @ResponseBody
    public void getImage (HttpServletResponse response) {
        try {
            // 读取图片文件
            ClassPathResource resource = new ClassPathResource("static/meijing.jpg");
            FileInputStream fis = new FileInputStream(resource.getFile());
            // 设置响应头，指定内容类型为图片
            response.setContentType("image/jpeg");
            response.setContentLength((int) resource.getFile().length());
            // 将图片数据写入响应输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            fis.close();
        } catch (IOException e) {
            throw new MyException(e.getMessage());
        }
    }
}
